


from flask import Blueprint,request,jsonify,render_template
from common.models.login import Login
from flask import jsonify
from application import db
from common.models.shop import ShopDetail
from sqlalchemy import  func
from common.models.citys import City
from flask import g


api_main = Blueprint('api_page',__name__)
@api_main.route('/login',methods=['GET','POST'])

def login():

    # POST方式请求
    if request.method == "POST":

        resp = {'code':200,'msg':'操作成功','data':{}}

        req = request.values

        account = req['account'] if 'account' in req else ''

        cookies = req['cookies'] if 'cookies' in req else ''

        if len( account ) < 1:
            return '<script>alert("添加失败");location.href="/api/login?account={0}"</script>'.format(account)

        shop_info = Login.query.filter_by( account= account).first()

        shop_info.account = account

        shop_info.cookies = cookies

        db.session.add( shop_info )

        db.session.commit()

        return '<script>alert("添加成功!!!");location.href="info"</script>'


    # GET获取数据

    req = request.values

    # 账号
    account = req['account'] if 'account' in req else ''


    if len( account )<0:

        return '<script>alert("无效账号!!!");location.href="info"</script>'


    #分配数据

    data = {

        'account':account
    }

    # 模板渲染
    return render_template('login.html',**data)




# 店铺详情信息
@api_main.route('/shop',methods=['POST','GET'])

def shop():

    try:

        resp = {'code':200,'msg':'操作成功','data':{}}

        if request.method == 'POST':

            req = request.values

            uid = req['uid'] if 'uid' in req else 0

            title = req['title'] if 'title' in req else ''

            shop_id = req['shop_id'] if 'shop_id' in req else 0


            if int(uid)<1:

                resp['code'] = 4001

                resp['msg'] = '不符合规范的uid类型!!'

                return jsonify( resp )

            if len( title )< 1:

                resp['code'] = 4002

                resp['msg'] = '不符合规范店铺名称!!'

                return jsonify( resp )

            if int( shop_id )< 1:
                resp['code'] = 4003

                resp['msg'] = '不符合规范店铺id!!'

                return jsonify(resp)


            shop_info = ShopDetail()

            shop_info.title = title
            shop_info.uid = uid
            shop_info.shop_id = shop_id

            db.session.add( shop_info )

            db.session.commit()

            return jsonify( resp )
    except:
        # 数据库回滚
        db.session.rollback()

    try:

        # 随意领取任务
        query = ShopDetail.query

        # 随机取出一条cookie信息
        login_info = Login.query.order_by( func.rand()).filter( Login.cookies != '' ).limit(1).first()

        if login_info == None:

            resp['code'] = 4004
            resp['msg'] = '暂无领取任务,请更新cookie!!!'

            return jsonify( resp )


        # 随机取出一条商家id
        task_info = query.order_by(func.rand()).filter_by( status=0 ).limit(1).first()

        data = {

            'code':200,
            'id':task_info.id,
            'account':login_info.account,
            'cookies':login_info.cookies,
            'uid':task_info.uid,
            'shop_id':task_info.shop_id,
            'shop_name':task_info.title
        }

        # 重置任务状态

        status_info = ShopDetail.query.filter_by(id=task_info.id).first()

        status_info.status = 1

        db.session.add(status_info)

        db.session.commit()


        return jsonify ( data )


    except:

        # 任务更新完成
        resp['code'] = 4000

        resp['msg'] = '任务更新完成！！'

        return jsonify( resp )


@api_main.route('/details',methods=['POST','GET'])

def returnDetails():

    resp = {'code':200,'msg':'操作成功','data':{}}

    if request.method == 'POST':

        req = request.values

        uid = req['uid'] if 'uid' in req else 0

        nickname = req['nickname'] if 'nickname' in req else ''

        phone = req['phone'] if 'phone' in req else ''

        city = req['city'] if 'city' in req else ''

        url = req['url'] if 'url' in req else ''

        status = req['status'] if 'status' in req else 0

        if int( uid )< 0:

            resp['code'] = 4005

            resp['msg'] = '不符合规范的用户id!!'

            return jsonify( resp )

        if int( status )<0:

            resp['code'] = 4006
            resp['msg'] = '不符合状态规则！！'
            return jsonify( resp )


        query = ShopDetail.query

        shop_info = query.filter_by( uid = uid ).first()

        shop_info.nickname = nickname

        shop_info.phone = phone

        shop_info.city = city

        shop_info.url = url

        shop_info.status = status

        db.session.add( shop_info )

        db.session.commit()

    return jsonify( resp )


@api_main.route('/info')

def checkCookie():

    # 查询登录信息
    login_info = Login.query.all()

    items = []

    for item in login_info:

        if len( item.cookies) == 0:

            cookies = ''

        else:

            cookies = item.cookies.split(';')[7]

        items.append( dict( id=item.id, account = item.account, cookies=cookies ))

    data = dict( info=items)

    return render_template('info.html',**data)



@api_main.route('/iframe',methods=['POST','GET'])

def Iframe():

    return render_template('iframe.html')

@api_main.route('/image',methods=['POST','GET'])

def Image():

    req = request.values

    username = req['username'] if 'username' in req else ''

    callback_target = 'window.parent.upload'

    if len( username )==0:

        return '<script> type="text/javascript">{0}.error("{1}")</script>'.format( callback_target,"用户名无效!!")

    return '<script> type="text/javascript">{0}.success("{1}")</script>'.format( callback_target,username)



   # return render_template('iframe.html')


# 城市联动
@api_main.route('/city',methods=['POST','GET'])

def getCity( ):

    city_info = City()

    data = city_info.query.filter( City.upid == 0 )

    context = {'citylist':data}

    return render_template('city.html',**context)

# 定义空字符串
@api_main.route('/getcity',methods=['POST','GET'])
def getCitys():

    if request.method == "POST":

        resp = {'code':200,'msg':'操作成功','data':{}}

        req = request.values

        level = int( req['id']) if 'id' in req else None

        if int(level) == 0:

            resp['msg'] = '请选择城市分类'

            resp['code'] = -1

            return jsonify( resp )

        # 获取城市名称
        name = City.query.filter_by( id = level ).first()

        city_info = City()

        data = city_info.query.filter( City.upid == level ).all()

        items = []

        for v in data:

            items.append( dict( id = v.id,name=v.name) )

        resp['data'] = items

        return jsonify( resp )





